var http = require('http');
var fs = require('fs');
const path = require('path');
const querystring = require('querystring');

var formidable = require('formidable');
// 包含上传表单的html文件
var upload_html = fs.readFileSync("upload_file.html");
var error_html = fs.readFileSync("./webpage/error.html");
var nofile_html = fs.readFileSync("./webpage/nofile.html");
// 将其替换为保存上传文件的位置
var upload_path = "files";

http.createServer(function (req, res) {
    if (req.url == '/uploadform') {
        res.writeHead(200);
        res.write(upload_html);
        console.log('正在上传...');
        return res.end();
    } else if (req.url == '/fileupload' && req.method.toLowerCase() == 'post') {
        res.writeHead(200, { 'content-type': 'text/plain;charset=utf-8' });
        // 解析并保存文件(使用原生解析方式)
        //parseFile(req, res);
        var form = new formidable.IncomingForm();
        form.parse(req, function (err, fields, files) {
            // oldpath：文件保存到的临时文件夹
            var oldpath = files.file.filepath;
            var newpath = "./" + upload_path + "/" + files.file.originalFilename;
            // 将文件复制到新位置
            fs.rename(oldpath, newpath, function (err) {
                try {
                    res.end(get_host_ip_port() + "/" + upload_path + "/" + files.file.originalFilename);
                    if (!files.file.originalFilename) {
                        console.log("上传失败！ \n上传文件为空");
                    } else {
                        console.log('上传成功！\n' + newpath);
                    }
                } catch (err) {
                    console.log(err.message);
                }
            });
        });
    } else if (req.url == "/" + upload_path) {
        res.writeHead(200, {
            'content-type': 'text/html;charset=utf-8'
        });
        travel("./" + upload_path, function (filename) {
            var url = get_host_ip_port() + "/" + upload_path + "/" + filename;
            res.write("<a href=" + url + ">" + filename + "</a><br>");
        });
        res.end();
    } else {
        // 先对特殊符号和中文进行解码
        let decode_url = decodeURIComponent(req.url);
        console.log(decode_url);
        // 展示任何静态资源文件
        fs.readFile("." + decode_url, function (err, data) {
            if (decode_url.indexOf("/" + upload_path + "/") != -1) {
                res.writeHead(200, { 'content-type': 'text/plain;charset=utf-8' });
                res.end(data);
            } else if (decode_url.indexOf("/webpage/") != -1) {
                res.writeHead(200, { 'content-type': 'text/html;charset=utf-8' });
                if (!data) {
                    res.write(nofile_html);
                }
                res.end(data);
            } else {
                res.writeHead(200, { 'content-type': 'text/html;charset=utf-8' });
                res.write(error_html);
                return res.end();
            }
        });
    }
}).listen(8888, () => {
    console.log('Server running at ' + get_host_ip_port());
});

function travel(dir, callback) {
    fs.readdirSync(dir).forEach((file) => {
        var pathname = path.join(dir, file)
        if (fs.statSync(pathname).isDirectory()) {
            travel(pathname, callback)
        } else {
            callback(file)
        }
    })
}

function get_host_ip_port() {
    return "http://101.43.241.226:8888";
}

function parseFile(req, res) {
    req.setEncoding('binary');
    var body = ''; // 文件数据
    var fileName = ''; // 文件名
    // 边界字符串
    var boundary = req.headers['content-type'].split('; ')[1].replace('boundary=', '');
    req.on('data', function (chunk) {
        body += chunk;
    });

    req.on('end', function () {
        var file = querystring.parse(body, '\r\n', ':')
        //获取文件名
        var fileInfo = file['Content-Disposition'].split(';');
        for (value in fileInfo) {
            if (fileInfo[value].indexOf("filename=") != -1) {
                var removeSpaceStr = fileInfo[value].replace(/\s*/g, "");
                fileName = removeSpaceStr.substring(9, removeSpaceStr.length);
                if (fileName.indexOf('\\') != -1) {
                    fileName = fileName.substring(fileName.lastIndexOf('\\') + 1);
                }
            }
        }
        var entireData = body.toString();

        contentType = file['Content-Type'].substring(1);

        //获取文件二进制数据开始位置，即contentType的结尾
        var upperBoundary = entireData.indexOf(contentType) + contentType.length;
        var shorterData = entireData.substring(upperBoundary);

        // 替换开始位置的空格
        var binaryDataAlmost = shorterData.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

        // 去除数据末尾的额外数据，即: "--"+ boundary + "--"
        var binaryData = binaryDataAlmost.substring(0, binaryDataAlmost.indexOf('--' + boundary + '--'));

        // 保存文件
        fs.writeFile("./" + upload_path + "/" + fileName, binaryData, 'binary', function (err) {
            res.end(get_host_ip_port() + "/" + upload_path + "/" + fileName);
            console.log('上传成功！' + fileName);
        });
    });
}

process.on('uncaughtException', err => {
    console.error('有一个未捕获的错误', err);
    //process.exit(1) //强制性的（根据 Node.js 文档）
})
